const UserModule = require("../database/user");
const { alter, getData } = require("../utils/network");

function login(req, response, next) {
  try {
    const axios = require("axios");
    // console.log(req.body.code);
    axios
      .get(
        `https://api.weixin.qq.com/sns/jscode2session?appid=${自行配置}&secret=${自行配置}&js_code=${req.body.code}&grant_type=authorization_code`
      )
      .then(async (res) => {
        const code = res.data;
        // console.log("res.code", code);
        if (code.openid && code.session_key) {
          const result = await UserModule.findOne({
            where: {
              openId: code.openid,
            },
          });

          if (result) {
            result.session_key = code.session_key;
            result.save();
            response.status(201).json({
              msg: "登录成功",
              info: result,
            });
          } else {
            const result = await UserModule.create(code);
            response.status(201).json({
              msg: "注册成功",
              info: result,
            });
          }
        } else {
          response.status(400).json({
            msg: "没有获取到openid",
          });
        }
        // console.log("code", res.data);
      });
  } catch (error) {
    next({ msg: "登录接口出错", error });
  }
}

function getUserInfo(req, res, next) {
  getData(req, res, next, UserModule);
}

function infoComplete(req, res, next) {
  delete req.openid;
  alter(req, res, next, UserModule, {
    searchParam: ["openid"],
    alterParam: [...Object.keys(req.body)],
  });
}

module.exports = {
  getUserInfo,
  login,
  infoComplete,
};
